<?php

namespace App\Http\Controllers\Api;

use App\Models\MemberLabel;
use App\Repositories\Api\MemberRepository;
use App\Repositories\WechatRepository;
use Cache;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class LoginController extends MiniAppController
{
    private $memberRep;

    public function __construct(MemberRepository $memberRep)
    {
        parent::__construct();
        $this->memberRep = $memberRep;
    }

    public function index(Request $request)
    {
        //接收参数
        $code = $request->post('code');
        if (!isset($code)) {
            return $this->apiResponse->error("code 异常,请稍后再试", 400);
        }

        try {
            $wechatRepository = new WechatRepository();
            $wxSession = $wechatRepository->toSession($code);

            if (isset($wxSession['errcode']))//解析错误
                return $this->apiResponse->error('' . $wxSession['errmsg'], 500);

            $shop_supplier_id = intval($request->post("shop_id"));

            if (empty($member)) {
                $mData['gender'] = 0;
                $mData['weapp_openid'] = $wxSession['openid'];
                $mData['reg_ip'] = request()->ip();
                $mData['subscribe_scene'] = $request->post("scene") ?? "";

                $res = $this->memberRep->saveOrUpdate($mData);
//                $member = $this->memberRep->adminLogin(null, $wxSession['openid']);
            } else if ($member && !$member['weapp_openid']) {
                $this->memberRep->saveOrUpdate(['weapp_openid' => $wxSession['openid']], $member['id']);
            }
            $member = $this->memberRep->adminLogin(null, $wxSession['openid']);

            //更新对应的标签
            if ($shop_supplier_id && empty($member['tags'])) {
                $type = $shop_supplier_id == 10001 ? 2 : 1;
                if (!MemberLabel::query()->where(['uid' => $member['id'], 'type' => $type])->value("id")) {
                    MemberLabel::create([
                        'type' => $type,
                        'uid' => $member['id']
                    ]);
                    $member = $this->memberRep->adminLogin(null, $wxSession['openid']);
                }
            }

            /*
             *  is_new  2: 后台 1： 走前台
             */
            Cache::set("session_key_" . $member['id'], $wxSession['session_key']);
            return $this->apiResponse->success($member);
        } catch (Exception | GuzzleException $e) {
            Log::error(
                'decode error',
                [
                    'messages' => $e->getMessage() . '::' . json_encode(Request()->all()),
                    'code' => $e->getCode(),
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                ]
            );
            $errorMessage = $e->getMessage();
            if ($errorMessage == 'The given payload is invalid.') {
                return $this->apiResponse->error('解码失败，请重试' . $errorMessage, 505);
            }
            return $this->apiResponse->error('执行失败:' . $errorMessage, 500);
        }
    }

    /**
     * Api 图形验证码
     */
    public function captcha()
    {
        return $this->apiResponse->success([
            'url' => app('captcha')->create('default', true)
        ], 'success', 200, []);
    }
}
